package com.hcinfos.gsoo.ui;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.Platform.ShareParams;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;

import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeAddress;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.GeocodeSearch.OnGeocodeSearchListener;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.baidu.navisdk.BaiduNaviManager;
import com.baidu.navisdk.BNaviEngineManager.NaviEngineInitListener;
import com.baidu.navisdk.BaiduNaviManager.OnStartNavigationListener;
import com.baidu.navisdk.comapi.routeplan.RoutePlanParams.NE_RoutePlan_Mode;
import com.baidu.navisdk.util.verify.BNKeyVerifyListener;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.hcinfos.gsoo.GsooApplication;
import com.hcinfos.gsoo.R;
import com.hcinfos.gsoo.config.Common;
import com.hcinfos.gsoo.config.Constants;
import com.hcinfos.gsoo.config.Urls;
import com.hcinfos.gsoo.enity.Menu;
import com.hcinfos.gsoo.enity.UrlImage;
import com.hcinfos.gsoo.enity.ViewSuppDetail;
import com.hcinfos.gsoo.enity.ViewSuppSearchExt;
import com.hcinfos.gsoo.https.HttpClientUtil;
import com.hcinfos.gsoo.interaze.DialogCallBack;
import com.hcinfos.gsoo.util.DialogUtil;
import com.hcinfos.gsoo.util.ImageUtil;
import com.hcinfos.gsoo.util.UtilHttp;
import com.hcinfos.gsoo.util.ImageUtil.ImageCallback;
import com.hcinfos.gsoo.util.LogUtil;
import com.hcinfos.gsoo.util.SharePreferenceUtil;
import com.hcinfos.gsoo.view.PopMenu;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

/**
 * 店铺详情
 * 
 * @author john
 * 
 */
public class ShopDetailActivity extends Activity implements OnClickListener,
		OnGeocodeSearchListener {

	private TextView reg_tv;
	private ImageButton left_ib;
	private TextView center_tv;
	private ImageView right_img;

	private TextView address;
	private PopMenu popMenu;
	private TextView shopName;

	private RelativeLayout call_rl;
	private TextView call_num;
	private Activity activity;
	private RelativeLayout route_rl;

	private EditText report_et;
	private EditText report_contact;
	private RelativeLayout report_rl;
	private Dialog report_dialog;
	private Button confirm_dialog_ok_btn;
	private Button confirm_dialog_cancel_btn;
	private TextView averge;
	private TextView appraise;
	private LinearLayout star_ll;
	private TextView intro_detail;
	private ImageView shopimg;

	private GsooApplication app;
	private GeoPoint p1 = null;
	private String cityName = null;
	private SharePreferenceUtil util;
	private Context context;

	private final int DO_REPORT_SUCCESS = 0x1120;
	private final int DO_REPORT_FAIL = DO_REPORT_SUCCESS + 1;
	private final int LOGIN_RESULT_CODE = 0x4444;
	private final int CHECK_USER_ONLINE = LOGIN_RESULT_CODE + 1;
	private final int CRAW_DATA_SUCCESS = LOGIN_RESULT_CODE + 2;
	private final int CRAW_DATA_FAIL = LOGIN_RESULT_CODE + 3;
	private final int DETAIL_SUCCESS = LOGIN_RESULT_CODE + 4;
	private final int DETAIL_FAIL = LOGIN_RESULT_CODE + 5;

	private boolean isSelfData = true;

	private String lat = null, lng = null;

	private MapView mapView;
	private AMap aMap;
	private GeocodeSearch geocodeSearch;

	private Dialog crawDataDialog;
	private String suppId;

	private RelativeLayout update_rl;
	private RelativeLayout upload_rl;
	private RelativeLayout comment_rl;
	private RelativeLayout addInfo_rl;

	private ObjectMapper mapper;
	private Dialog waitDialog;

	private final static String ACCESS_KEY = "29E5B7Fd813e14a80e6c63b174d6135a";
	private boolean mIsEngineInitSuccess = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		int width = this.getWindowManager().getDefaultDisplay().getWidth();
		// 初始化导航引擎
		BaiduNaviManager.getInstance().initEngine(this, getSdcardDir(),
				mNaviEngineInitListener, ACCESS_KEY, mKeyVerifyListener);

		Common.PROPORTION = width / 320f;
		Common.WIDTH = width;
		activity = this;
		context = this;
		mapper = new ObjectMapper();
		crawDataDialog = DialogUtil.createProgressDialog(this, "提示",
				"数据采集中,请稍等!");
		waitDialog = DialogUtil.createProgressDialog(this, "提示", "数据获取中!");
		// api = WXAPIFactory.createWXAPI(this, Constants.WECHAT_ID);
		util = new SharePreferenceUtil(this, "setting");
		cityName = util.loadStringSharedPreference("cityName");
		app = (GsooApplication) getApplication();
		setContentView(R.layout.activity_shopdetail);
		mapView = (MapView) findViewById(R.id.mapView);
		mapView.setClickable(false);
		mapView.onCreate(savedInstanceState);// 此方法必须重写
		if (aMap == null) {
			aMap = mapView.getMap();
		}
		geocodeSearch = new GeocodeSearch(this);
		geocodeSearch.setOnGeocodeSearchListener(this);
		initRes();
	}

	private NaviEngineInitListener mNaviEngineInitListener = new NaviEngineInitListener() {
		public void engineInitSuccess() {
			mIsEngineInitSuccess = true;
		}

		public void engineInitStart() {
		}

		public void engineInitFail() {
		}
	};

	private BNKeyVerifyListener mKeyVerifyListener = new BNKeyVerifyListener() {

		@Override
		public void onVerifySucc() {
		}

		@Override
		public void onVerifyFailed(int arg0, String arg1) {
//			Toast.makeText(ShopDetailActivity.this, "key校验失败",
//					Toast.LENGTH_LONG).show();
		}
	};

	/**
	 * 启动GPS导航. 前置条件：导航引擎初始化成功
	 */
	private void launchNavigator(double startLat, double startLng,
			double endLat, double endLng) {
		// 这里给出一个起终点示例，实际应用中可以通过POI检索、外部POI来源等方式获取起终点坐标
		BaiduNaviManager.getInstance().launchNavigator(this, startLat,
				startLng, "", endLat, endLng, "",
				NE_RoutePlan_Mode.ROUTE_PLAN_MOD_MIN_TIME, // 算路方式
				true, // 真实导航
				BaiduNaviManager.STRATEGY_FORCE_ONLINE_PRIORITY, // 在离线策略
				new OnStartNavigationListener() { // 跳转监听

					@Override
					public void onJumpToNavigator(Bundle configParams) {
						Intent intent = new Intent(ShopDetailActivity.this,
								BNavigatorActivity.class);
						intent.putExtras(configParams);
						startActivity(intent);
					}

					@Override
					public void onJumpToDownloader() {
					}
				});
	}

	private String getSdcardDir() {
		if (Environment.getExternalStorageState().equalsIgnoreCase(
				Environment.MEDIA_MOUNTED)) {
			return Environment.getExternalStorageDirectory().toString();
		}
		return null;
	}

	private void initRes() {

		addInfo_rl = (RelativeLayout) findViewById(R.id.addInfo_rl);
		addInfo_rl.setOnClickListener(this);

		update_rl = (RelativeLayout) findViewById(R.id.update_rl);
		update_rl.setOnClickListener(this);
		upload_rl = (RelativeLayout) findViewById(R.id.upload_rl);
		upload_rl.setOnClickListener(this);
		comment_rl = (RelativeLayout) findViewById(R.id.comment_rl);
		comment_rl.setOnClickListener(this);

		LayoutInflater inflater = getLayoutInflater();
		left_ib = (ImageButton) findViewById(R.id.left_ib);
		left_ib.setOnClickListener(this);
		reg_tv = (TextView) findViewById(R.id.reg_tv);
		reg_tv.setVisibility(View.GONE);
		center_tv = (TextView) findViewById(R.id.center_tv);
		center_tv.setText("店铺详情");
		right_img = (ImageView) findViewById(R.id.right_img);
		right_img.setVisibility(View.VISIBLE);
		right_img.setImageResource(R.drawable.share_btn);
		right_img.setOnClickListener(this);
		address = (TextView) findViewById(R.id.address);
		address.setBackgroundColor(Color.argb(125, 0, 0, 0));

		popMenu = new PopMenu(this);
		popMenu.setOnItemClickListener(popmenuItemClickListener);
		int[] res = { R.drawable.sns_sina_icon, R.drawable.sns_weixin_icon,
				R.drawable.sns_weixin_timeline_icon };
		String[] name = { "微博", "微信", "朋友圈" };
		for (int i = 0; i < res.length; i++) {
			popMenu.addItem(new Menu(name[i], res[i]));
		}

		call_rl = (RelativeLayout) findViewById(R.id.call_rl);
		call_rl.setOnClickListener(this);
		call_num = (TextView) findViewById(R.id.call_num);

		// mapController.setScrollGesturesEnabled(false);
		// mapController.setZoomGesturesEnabled(false);

		report_rl = (RelativeLayout) inflater.inflate(
				R.layout.report_dialog_view, null);
		report_et = (EditText) report_rl.findViewById(R.id.report_et);
		report_contact = (EditText) report_rl.findViewById(R.id.contact_et);
		confirm_dialog_cancel_btn = (Button) report_rl
				.findViewById(R.id.confirm_dialog_cancel_btn);
		confirm_dialog_cancel_btn.setOnClickListener(this);
		confirm_dialog_ok_btn = (Button) report_rl
				.findViewById(R.id.confirm_dialog_ok_btn);
		confirm_dialog_ok_btn.setText("提交");
		confirm_dialog_ok_btn.setOnClickListener(this);

		route_rl = (RelativeLayout) findViewById(R.id.route_rl);
		route_rl.setOnClickListener(this);
		shopName = (TextView) findViewById(R.id.shopName);
		averge = (TextView) findViewById(R.id.averge);
		appraise = (TextView) findViewById(R.id.appraise);
		star_ll = (LinearLayout) findViewById(R.id.star_ll);
		intro_detail = (TextView) findViewById(R.id.intro_detail);
		shopimg = (ImageView) findViewById(R.id.shopimg);
		shopimg.setOnClickListener(this);
		im_iv = (ImageView) findViewById(R.id.im_iv);
		im_iv.setOnClickListener(this);
		im_iv.setVisibility(View.GONE);
	}

	private ViewSuppSearchExt detail;
	private String url;
	private ImageView im_iv;

	private void initData() {
		star_ll.removeAllViews();

		if (GsooApplication.tempSuppExt != null) {
			detail = GsooApplication.tempSuppExt;
		}
		if (detail == null) {
			if (suppId != null) {
				obtainInfoById(suppId);
			}
			return;
		}
		refreshData();

	}

	private void refreshData() {
		if (detail.getDataType() != null
				&& detail.getDataType().equals(ViewSuppSearchExt.TYPES[1])) {
			isSelfData = false;
			addInfo_rl.setVisibility(View.GONE);
			upload_rl.setVisibility(View.GONE);
			comment_rl.setVisibility(View.GONE);
			update_rl.setVisibility(View.GONE);
		} else {
			isSelfData = true;
			addInfo_rl.setVisibility(View.GONE);
			upload_rl.setVisibility(View.VISIBLE);
			comment_rl.setVisibility(View.VISIBLE);
			update_rl.setVisibility(View.VISIBLE);
		}
		if (detail.getGgnumber() == null) {
			im_iv.setVisibility(View.GONE);
		} else {
			// if (userInfo != null
			// && userInfo.getUserId() != null
			// && IMUtil.handJIDToString(userInfo.getUserId()).equals(
			// detail.getGgnumber())) {
			// im_iv.setVisibility(View.GONE);
			// } else {
			// im_iv.setVisibility(View.VISIBLE);
			// new Thread(new Runnable() {
			//
			// @Override
			// public void run() {
			// short i = IsUserOnLine(detail.getGgnumber());
			// Message msg = handler.obtainMessage();
			// msg.what = CHECK_USER_ONLINE;
			// msg.obj = i + "";
			// handler.sendMessage(msg);
			// LogUtil.d("wxf", "is onLine=" + i);
			// }
			// }).start();
			// }

		}

		shopName.setText(detail.getSuppName());
		averge.setText("人均：￥"
				+ (detail.getConsumptionPer() == null ? "暂无" : detail
						.getConsumptionPer()));
		Double score1 = detail.getScore1();
		Double score2 = detail.getScore2();
		Double score3 = detail.getScore3();
		String score1Str = score1 == null ? "暂无" : String.valueOf(score1);
		String score2Str = score2 == null ? "暂无" : String.valueOf(score2);
		String score3Str = score3 == null ? "暂无" : String.valueOf(score3);
		appraise.setText("口味:" + score1Str + "  环境:" + score2Str + "  服务:"
				+ score3Str);
		// 评分
		Double d = detail.getScoreSum();
		LogUtil.d("wxf", "getScoreSum:" + d);
		if (d == null) {
			for (int i = 0; i < 5; i++) {
				ImageView view = new ImageView(this);
				view.setImageResource(R.drawable.star_gay);
				star_ll.addView(view);
			}
		} else {
			int num = 0;
			try {
				num = (int) d.doubleValue();
				LogUtil.d("wxf", "socreSum:" + d);
			} catch (Exception e) {
				LogUtil.d("wxf", "e:" + e.toString());
				num = 0;
			}
			if (num >= 5) {
				for (int i = 0; i < 5; i++) {
					ImageView view = new ImageView(this);
					view.setImageResource(R.drawable.star_yel);
					star_ll.addView(view);
				}
			} else {
				if (num == 0) {
					for (int i = 0; i < 5; i++) {
						ImageView view = new ImageView(this);
						view.setImageResource(R.drawable.star_gay);
						star_ll.addView(view);
					}
				} else {
					for (int i = 0; i < 5; i++) {
						ImageView view = new ImageView(this);
						if (i < num) {
							view.setImageResource(R.drawable.star_yel);
						} else {
							view.setImageResource(R.drawable.star_gay);
						}
						star_ll.addView(view);
					}
				}
			}
		}
		// ======over==================
		String tel = detail.getTelPhone() == null ? "暂无" : detail.getTelPhone();
		call_num.setText(tel);
		String intro = detail.getSupInfo() == null ? "暂无" : detail.getSupInfo();
		intro_detail.setText(intro);
		url = Constants.SERVER + detail.getImgAddr() + Constants.IMG_THUMB_DIR
				+ detail.getImgId() + ".jpg";
		if (isSelfData) {
			ImageUtil.setThumbnailView(url, shopimg, ShopDetailActivity.this,
					new ImageCallback() {

						@Override
						public void loadImage(Bitmap bitmap, String imagePath) {
							shopimg.setImageBitmap(bitmap);
						}
					}, true, true);

		} else {
			List<UrlImage> images = detail.getPhotos();
			if (images != null && images.size() > 0) {
				ImageUtil.setThumbnailView(images.get(0).getUrl(), shopimg,
						ShopDetailActivity.this, new ImageCallback() {

							@Override
							public void loadImage(Bitmap bitmap,
									String imagePath) {
								shopimg.setImageBitmap(bitmap);
							}
						}, true, true);
			} else {
				shopimg.setBackgroundResource(R.drawable.tc_shop_default_logo);
			}
		}
		lat = detail.getLat();
		lng = detail.getLon();
		String addressStr = detail.getAddr();
		if (lat == null || lng == null || lat.length() == 0
				|| lng.length() == 0) {
			if (addressStr != null) {
				// 地址反查
				// mSearch.geocode(addressStr, cityName);
				GeocodeQuery query = new GeocodeQuery(addressStr, cityName);// 第一个参数表示地址，第二个参数表示查询城市，中文或者中文全拼，citycode、adcode，
				geocodeSearch.getFromLocationNameAsyn(query);// 设置同步地理编码请求
			} else {
				aMap.animateCamera(CameraUpdateFactory
						.newCameraPosition(new CameraPosition(new LatLng(
								31.208862, 121.592514), 18, 0, 30)));
			}
		} else {
			double lt = 0;
			double lg = 0;
			LogUtil.d("wxf", "lat:" + lat + ",lng:" + lng);
			try {
				lt = Double.parseDouble(lat);
				lg = Double.parseDouble(lng);

			} catch (Exception e) {
				LogUtil.d("wxf", "e:" + e.toString());
			}
			aMap.animateCamera(CameraUpdateFactory
					.newCameraPosition(new CameraPosition(new LatLng(lt, lg),
							18, 0, 30)));
		}
		address.setText(addressStr);
	}

	@Override
	protected void onResume() {
		ShareSDK.initSDK(this);
		detail = (ViewSuppSearchExt) getIntent().getSerializableExtra(
				"shopDetail");
		suppId = getIntent().getStringExtra("suppId");
		initData();
		super.onResume();
		mapView.onResume();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		mapView.onDestroy();
	}

	@Override
	protected void onPause() {
		super.onPause();
		mapView.onPause();
	}

	private Intent intent;

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.addInfo_rl:
			crawData(detail.getPoid(), detail.getTypeId(),
					GsooApplication.cityName, null);
			break;
		case R.id.right_img:
			popMenu.showAsDropDown(v);
			break;
		case R.id.comment_rl:
			intent = new Intent(ShopDetailActivity.this,
					CommentListActivity.class);
			intent.putExtra("detail", detail);
			startActivity(intent);
			break;
		case R.id.call_rl:
			String numStr = call_num.getText().toString();
			if (numStr == null || numStr.length() == 0) {
				Toast.makeText(ShopDetailActivity.this, "暂无电话信息", 500).show();
			} else {
				doCall();
			}
			break;
		case R.id.left_ib:
			finish();
			break;
		case R.id.upload_rl:
			intent = new Intent(ShopDetailActivity.this,
					UploadImgActivity.class);
			intent.putExtra("shopDetail", detail);
			startActivity(intent);
			break;
		case R.id.update_rl:
			intent = new Intent(ShopDetailActivity.this, UpdateActivity.class);
			intent.putExtra("detail", detail);
			startActivity(intent);
			break;

		case R.id.confirm_dialog_ok_btn:
			if (report_dialog != null)
				report_dialog.dismiss();
			doReport();// 提交检举
			break;
		case R.id.confirm_dialog_cancel_btn:
			if (report_dialog != null)
				report_dialog.dismiss();
			break;
		case R.id.route_rl:
			if (lat == null || GsooApplication.lat == null) {
				Toast.makeText(ShopDetailActivity.this, "地理位置信息不全", 500).show();
				return;
			}
			launchNavigator(GsooApplication.lat, GsooApplication.lng,
					Double.parseDouble(lat), Double.parseDouble(lng));
			// intent = new Intent(ShopDetailActivity.this,
			// RouteActivity.class);
			// intent.putExtra("lat", lat);
			// intent.putExtra("lng", lng);
			// startActivity(intent);
			break;
		case R.id.shopimg:

			if (detail.getDataType() != null
					&& detail.getDataType().equals(ViewSuppSearchExt.TYPES[1])) {
				if (detail.getPhotos() != null
						&& detail.getPhotos().size() != 0) {
					intent = new Intent(ShopDetailActivity.this,
							ShopImgListActivity.class);
					intent.putExtra("shopDetail", detail);
					startActivity(intent);
				} else {
					Toast.makeText(this, "暂无图片", 500).show();
				}
			} else {
				intent = new Intent(ShopDetailActivity.this,
						ShopImgListActivity.class);
				intent.putExtra("shopDetail", detail);
				startActivity(intent);

			}
			break;
		case R.id.coupon_tv:
			intent = new Intent(ShopDetailActivity.this,
					ShopCouponActivity.class);
			intent.putExtra("shopDetail", detail);
			startActivity(intent);
			break;
		case R.id.im_iv:

			break;
		}
	}

	/**
	 * 一键采集数据
	 */
	private void crawData(final String poid, final String typeId,
			final String cityName, final String cityId) {

		crawDataDialog.show();

		new Thread(new Runnable() {

			@Override
			public void run() {

				String result = null;
				try {
					LogUtil.d("wxf", "crawData =  poid," + poid + ",typeId="
							+ typeId);
					result = HttpClientUtil.getFromWebByHttpClient(context,
							Urls.CRAW_BY_POID + "cbpi_poiId=" + poid
									+ "&cbpi_typeId=" + typeId
									+ "&cbpi_cityName=" + cityName);
					LogUtil.d("wxf", "result:" + result);
					if (result != null) {
						JSONObject obj = new JSONObject(result);
						int state = obj.getInt("state");
						if (state == 200) {
							suppId = obj.getJSONObject("data").getString(
									"suppId");
							handler.sendEmptyMessage(CRAW_DATA_SUCCESS);
							LogUtil.d("wxf", "suppId=" + suppId);
						} else {
							handler.sendEmptyMessage(CRAW_DATA_FAIL);
						}

					} else {
						handler.sendEmptyMessage(CRAW_DATA_FAIL);
					}
				} catch (Exception e) {
					handler.sendEmptyMessage(CRAW_DATA_FAIL);
				}

			}
		}).start();
	}

	/**
	 * 
	 */

	/**
	 * 提交检举
	 */
	private void doReport() {
		new Thread(new Runnable() {

			@Override
			public void run() {

				String reportStr = report_et.getText().toString();
				String telStr = report_contact.getText().toString();
				String result;
				try {
					result = HttpClientUtil.getFromWebByHttpClient(
							context,
							Urls.SHOP_FEEDBACK + "feedback.fdSuppId="
									+ detail.getId() + "&feedback.fdSuppName="
									+ detail.getSuppName()
									+ "&feedback.reason=" + reportStr
									+ "&feedback.contact=" + telStr);
					LogUtil.d("wxf", "result:" + result);
					if (result != null) {
						JSONObject obj = new JSONObject(result);
						int state = obj.getInt("state");
						String message = obj.getString("message");
						Message msg = handler.obtainMessage();
						msg.what = DO_REPORT_SUCCESS;
						msg.obj = message;
						handler.sendMessage(msg);

					} else {
						Message msg = handler.obtainMessage();
						msg.what = DO_REPORT_FAIL;
						handler.sendMessage(msg);
					}
				} catch (Exception e) {
					Message msg = handler.obtainMessage();
					msg.what = DO_REPORT_FAIL;
					handler.sendMessage(msg);
					LogUtil.d("wxf", "e:" + e.toString());
				}

			}
		}).start();
	}

	/**
	 * 根据id获取详情
	 */
	private void obtainInfoById(final String id) {
		waitDialog.show();
		HttpUtils http = UtilHttp.getHttpUtils(this);
		RequestParams params = new RequestParams();
		params.addBodyParameter("record.id", id);
		http.send(HttpRequest.HttpMethod.POST, Urls.FIND_SHOP_DETAIL, params,
				new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						LogUtil.e("wxf", arg0.toString());
						handler.sendEmptyMessage(DETAIL_FAIL);
					}

					@Override
					public void onSuccess(ResponseInfo<String> arg0) {
						LogUtil.d("wxf", "detail=" + arg0.result);
						try {

							String result = arg0.result;
							result = result.replaceAll("record.", "");
							detail = mapper.readValue(result,
									new TypeReference<ViewSuppSearchExt>() {
									});
							handler.sendEmptyMessage(DETAIL_SUCCESS);
						} catch (Exception e) {
							LogUtil.e("wxf", e.toString());
							handler.sendEmptyMessage(DETAIL_FAIL);
						}
					}

				});
	}

	Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case DO_REPORT_FAIL:
				Toast.makeText(context, "检举失败", 500).show();
				break;
			case DO_REPORT_SUCCESS:
				String str = "检举成功";
				if (msg.obj != null) {
					str = msg.obj.toString();
				}
				Toast.makeText(context, str, 500).show();
				break;
			case CHECK_USER_ONLINE:
				if (msg.obj != null) {
					String state = msg.obj.toString();
					if (state.equals("1")) {
						im_iv.setImageResource(R.drawable.im_icon_online);
						im_iv.setVisibility(View.VISIBLE);
					} else {
						im_iv.setImageResource(R.drawable.im_icon_offline);
						im_iv.setVisibility(View.VISIBLE);
					}
				}
			case CRAW_DATA_FAIL:
				crawDataDialog.dismiss();
				Toast.makeText(ShopDetailActivity.this, "采集失败", 500).show();
				break;
			case CRAW_DATA_SUCCESS:
				shopimg.setBackgroundResource(R.drawable.tc_shop_default_logo);
				GsooApplication.tempSuppExt = detail;
				detail.setId(suppId);
				detail.setDataType(ViewSuppSearchExt.TYPES[0]);
				crawDataDialog.dismiss();
				addInfo_rl.setVisibility(View.GONE);
				Toast.makeText(ShopDetailActivity.this, "采集成功", 500).show();
				break;
			case DETAIL_FAIL:
				waitDialog.dismiss();

				break;
			case DETAIL_SUCCESS:
				waitDialog.dismiss();
				refreshData();
				break;
			}
		};
	};

	private void doCall() {

		String str = call_num.getText().toString();
		Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + str));
		startActivity(intent);

	}

	private String shareContent;
	private String shareUrl;

	// 弹出菜单监听器
	OnItemClickListener popmenuItemClickListener = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			switch (position) {
			case 0:
				intent = new Intent(ShopDetailActivity.this,
						ShareEditActivity.class);
				intent.putExtra("shopDetail", detail);
				startActivity(intent);
				break;
			case 1:
				shareContent = "这里是#" + detail.getSuppName() + "#:#即搜中国#";
				wechatShare(1);
				// 发送给朋友
				break;
			case 2:
				// 分享到朋友圈
				shareContent = "这里是#" + detail.getSuppName() + "#:#即搜中国#";
				if (url == null || url.length() == 0) {
					Toast.makeText(context, "暂无图片url暂且不能分享", 500).show();
				} else {
					shareUrl = url;
					wechatShare(0);
				}
				break;
			}
			popMenu.dismiss();
		}
	};

	/**
	 * 微信分享
	 */
	private void wechatShare(int type) {

		String name = type == 0 ? WechatMoments.NAME : Wechat.NAME;
		Platform plat = ShareSDK.getPlatform(this, name);
		ShareParams sp = type == 0 ? getWechatMomentsShareParams()
				: getWechatShareParams();
		plat.share(sp);
		plat.setPlatformActionListener(new PlatformActionListener() {

			@Override
			public void onError(Platform arg0, int arg1, Throwable arg2) {

				LogUtil.e("wxf", arg2.toString());
			}

			@Override
			public void onComplete(Platform arg0, int arg1,
					HashMap<String, Object> arg2) {

				Toast.makeText(ShopDetailActivity.this, "分享成功", 500).show();
			}

			@Override
			public void onCancel(Platform arg0, int arg1) {

			}
		});
	}

	private ShareParams getWechatShareParams() {
		Wechat.ShareParams sp = new Wechat.ShareParams();
		sp.title = "即搜分享";
		sp.text = shareContent;
		sp.shareType = Platform.SHARE_TEXT;
		return sp;
	}

	private ShareParams getWechatMomentsShareParams() {
		WechatMoments.ShareParams sp = new WechatMoments.ShareParams();
		sp.title = "即搜分享";
		sp.text = shareContent;
		sp.imageUrl = shareUrl;
		sp.shareType = Platform.SHARE_IMAGE;
		return sp;
	}

	public short IsUserOnLine(String ggnumber) {
		String url = "http://www.gsoo.com:9090/plugins/presence/status?jid="
				+ ggnumber + "@121.199.15.125&type=xml";
		short shOnLineState = 0; // -不存在-
		try {
			URL oUrl = new URL(url);
			URLConnection oConn = oUrl.openConnection();
			if (oConn != null) {
				BufferedReader oIn = new BufferedReader(new InputStreamReader(
						oConn.getInputStream()));
				if (null != oIn) {
					String strFlag = oIn.readLine();
					oIn.close();
					if (strFlag.indexOf("type=\"unavailable\"") >= 0) {
						shOnLineState = 2;
					}
					if (strFlag.indexOf("type=\"error\"") >= 0) {
						shOnLineState = 0;
					} else if (strFlag.indexOf("priority") >= 0
							|| strFlag.indexOf("id=\"") >= 0) {
						shOnLineState = 1;
					}
				}
			}
		} catch (Exception e) {
			LogUtil.e("wxf", "e=" + e.toString());
		}

		return shOnLineState;
	}

	@Override
	public void onGeocodeSearched(GeocodeResult result, int rCode) {

		if (rCode == 0) {
			if (result != null && result.getGeocodeAddressList() != null
					&& result.getGeocodeAddressList().size() > 0) {
				GeocodeAddress address = result.getGeocodeAddressList().get(0);
				LatLonPoint latlngPoint = address.getLatLonPoint();
				aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
						new LatLng(latlngPoint.getLatitude(), latlngPoint
								.getLongitude()), 15));
			}
		}
	}

	@Override
	public void onRegeocodeSearched(RegeocodeResult result, int rCode) {

	}
}
